import 'dart:ui';

import 'package:flutter/material.dart';
import 'package:ducafe_ui_core/ducafe_ui_core.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:mesh/function/widgets/border_widget.dart';
import 'dart:async';

import '../../function/states/activity_state.dart';
import '../../function/states/user_state.dart';
import '../../function/models/activity_model.dart';
import '../../function/widgets/animated_tap_widget.dart';
import '../../function/widgets/report_dialog.dart';
import '../../function/widgets/toast_widget.dart';
import '../../function/widgets/login_dialog.dart';
import '../../function/routes/app_route_manager.dart';

/// 弹幕项数据模型
class BulletItem {
  final String id;
  final String content;
  final double top;
  final AnimationController animationController;
  final DateTime startTime;

  BulletItem({
    required this.id,
    required this.content,
    required this.top,
    required this.animationController,
    required this.startTime,
  });
}

/// 活动详情页面
class ActivityDetailPage extends StatefulWidget {
  final String activityId;

  const ActivityDetailPage({super.key, required this.activityId});

  @override
  State<ActivityDetailPage> createState() => _ActivityDetailPageState();
}

class _ActivityDetailPageState extends State<ActivityDetailPage>
    with TickerProviderStateMixin {
  late ActivityModel _currentActivity;
  late Timer _bulletTimer;
  final List<BulletItem> _activeBullets = [];
  int _bulletIdCounter = 0;
  Map<double, DateTime> _lastBulletTime = {}; // 每条线最后添加弹幕的时间

  @override
  void initState() {
    super.initState();
    _initializeActivityData();
    _startBulletSystem();
  }

  @override
  void dispose() {
    _bulletTimer.cancel();
    // 清理所有弹幕的动画控制器
    for (final bullet in _activeBullets) {
      bullet.animationController.dispose();
    }
    super.dispose();
  }

  /// 初始化活动数据
  void _initializeActivityData() {
    final activity = ActivityState.getActivityById(widget.activityId);
    if (activity != null) {
      _currentActivity = activity;
    } else {
      // 如果找不到活动，返回上一页
      AppRouteManager.goBack();
    }
  }

  /// 启动弹幕系统
  void _startBulletSystem() {
    // 立即添加一些初始弹幕，每条线一个
    final bulletRows = [25.h, 70.h, 115.h];
    for (int i = 0; i < bulletRows.length; i++) {
      Future.delayed(Duration(milliseconds: i * 1000), () {
        if (mounted) {
          _addNewBullet();
        }
      });
    }

    // 定期添加新弹幕
    _bulletTimer = Timer.periodic(const Duration(milliseconds: 1500), (timer) {
      if (mounted) {
        _addNewBullet();
      }
    });
  }

  /// 添加新弹幕
  void _addNewBullet() {
    final bullets = ActivityState.getActivityBullets(widget.activityId);
    if (bullets.isEmpty) return;

    // 随机选择一个弹幕内容
    final randomBullet = bullets[_bulletIdCounter % bullets.length];
    _bulletIdCounter++;

    // 弹幕行（25.h高度，20.h间距，在210.h容器中居中：67.5, 112.5, 157.5）
    final bulletRows = [67.5.h, 112.5.h, 157.5.h];

    // 找到可以添加弹幕的行（避免重叠）
    double? availableTop;
    final now = DateTime.now();

    // 强制轮询：每3个弹幕确保所有行都有机会
    if (_bulletIdCounter % 3 == 0) {
      // 每3个弹幕强制选择第三行
      availableTop = bulletRows[2]; // 第三行
    } else if (_bulletIdCounter % 3 == 1) {
      // 每3个弹幕强制选择第二行
      availableTop = bulletRows[1]; // 第二行
    } else {
      // 每3个弹幕强制选择第一行
      availableTop = bulletRows[0]; // 第一行
    }

    // 检查强制选择的行是否真的可用
    final lastTime = _lastBulletTime[availableTop];
    if (lastTime != null && now.difference(lastTime).inMilliseconds < 1000) {
      // 如果强制选择的行被占用，选择最久没有弹幕的行
      availableTop = bulletRows.reduce((a, b) {
        final timeA = _lastBulletTime[a] ?? DateTime(1970);
        final timeB = _lastBulletTime[b] ?? DateTime(1970);
        return timeA.isBefore(timeB) ? a : b;
      });
    }

    // 创建动画控制器
    final animationController = AnimationController(
      duration: const Duration(seconds: 8), // 弹幕从右到左的移动时间
      vsync: this,
    );

    // 创建弹幕项
    final bulletItem = BulletItem(
      id: 'bullet_${DateTime.now().millisecondsSinceEpoch}',
      content: randomBullet.content,
      top: availableTop,
      animationController: animationController,
      startTime: DateTime.now(),
    );

    // 记录这条线最后添加弹幕的时间
    _lastBulletTime[availableTop] = now;

    // 添加到活跃弹幕列表
    setState(() {
      _activeBullets.add(bulletItem);
    });

    // 启动动画
    animationController.forward().then((_) {
      // 动画完成后移除弹幕
      setState(() {
        _activeBullets.removeWhere((bullet) => bullet.id == bulletItem.id);
      });
      animationController.dispose();
    });
  }

  /// 处理发送弹幕
  void _handleSendBullet() {
    if (!UserState.checkLoginStatus()) {
      // 显示登录提示
      LoginDialog.show(context);
      return;
    }

    // 显示发送弹幕弹窗
    _showSendBulletDialog();
  }

  /// 显示发送弹幕弹窗
  void _showSendBulletDialog() {
    final TextEditingController controller = TextEditingController();

    showDialog(
      context: context,
      barrierDismissible: true,
      builder: (BuildContext context) {
        return Dialog(
          backgroundColor: Colors.transparent,
          child: Container(
            width: 320.w,
            padding: EdgeInsets.all(24.w),
            decoration: BoxDecoration(
              color: const Color(0xFF663507),
              borderRadius: BorderRadius.circular(20.r),
              border: Border.all(
                color: Colors.white.withOpacity(0.3),
                width: 1.w,
              ),
            ),
            child: Column(
              mainAxisSize: MainAxisSize.min,
              children: [
                // 标题
                Text('Send Bullet Chat')
                    .fontSize(18.sp)
                    .textColor(Colors.white)
                    .fontWeight(FontWeight.w600)
                    .fontFamily(
                      GoogleFonts.quicksand(
                        fontWeight: FontWeight.w600,
                      ).fontFamily,
                    )
                    .paddingBottom(20.h),

                // 输入框
                Container(
                  decoration: BoxDecoration(
                    color: Colors.white.withOpacity(0.1),
                    borderRadius: BorderRadius.circular(12.r),
                    border: Border.all(
                      color: Colors.white.withOpacity(0.3),
                      width: 1.w,
                    ),
                  ),
                  child: TextField(
                    controller: controller,
                    maxLines: 3,
                    maxLength: 50,
                    style: TextStyle(
                      color: Colors.white,
                      fontSize: 14.sp,
                      fontFamily: GoogleFonts.quicksand().fontFamily,
                    ),
                    decoration: InputDecoration(
                      hintText: 'Enter your bullet chat...',
                      hintStyle: TextStyle(
                        color: Colors.white.withOpacity(0.6),
                        fontSize: 14.sp,
                        fontFamily: GoogleFonts.quicksand().fontFamily,
                      ),
                      border: InputBorder.none,
                      contentPadding: EdgeInsets.all(16.w),
                      counterStyle: TextStyle(
                        color: Colors.white.withOpacity(0.6),
                        fontSize: 12.sp,
                      ),
                    ),
                  ),
                ),

                SizedBox(height: 20.h),

                // 按钮区域
                Row(
                  children: [
                    // 取消按钮
                    Expanded(
                      child: AnimatedTapWidget(
                        onTap: () => Navigator.of(context).pop(),
                        child: Container(
                          padding: EdgeInsets.symmetric(vertical: 12.h),
                          decoration: BoxDecoration(
                            color: Colors.white.withOpacity(0.1),
                            borderRadius: BorderRadius.circular(12.r),
                            border: Border.all(
                              color: Colors.white.withOpacity(0.3),
                              width: 1.w,
                            ),
                          ),
                          child:
                              Text('Cancel')
                                  .fontSize(14.sp)
                                  .textColor(Colors.white)
                                  .fontWeight(FontWeight.w500)
                                  .fontFamily(
                                    GoogleFonts.quicksand(
                                      fontWeight: FontWeight.w500,
                                    ).fontFamily,
                                  )
                                  .center(),
                        ),
                      ),
                    ),

                    SizedBox(width: 12.w),

                    // 发送按钮
                    Expanded(
                      child: AnimatedTapWidget(
                        onTap: () {
                          final text = controller.text.trim();
                          if (text.isNotEmpty) {
                            _sendBulletChat(text);
                            Navigator.of(context).pop();
                          } else {
                            ToastWidget.showWarning(
                              'Please enter bullet chat content',
                            );
                          }
                        },
                        child: Container(
                          padding: EdgeInsets.symmetric(vertical: 12.h),
                          decoration: BoxDecoration(
                            color: const Color(0xFFFF8A3C),
                            borderRadius: BorderRadius.circular(12.r),
                          ),
                          child:
                              Text('Send')
                                  .fontSize(14.sp)
                                  .textColor(Colors.white)
                                  .fontWeight(FontWeight.w600)
                                  .fontFamily(
                                    GoogleFonts.quicksand(
                                      fontWeight: FontWeight.w600,
                                    ).fontFamily,
                                  )
                                  .center(),
                        ),
                      ),
                    ),
                  ],
                ),
              ],
            ),
          ),
        );
      },
    );
  }

  void _handleUserAvatarTap(String userId) {
    if (userId.isEmpty) return;

    final currentUser = UserState.getCurrentUserInfo();
    if (currentUser != null && currentUser.userId == userId) {
      // 如果是当前用户，跳转到自己的用户中心
      AppRouteManager.navigateToUserCenter();
    } else {
      // 如果是其他用户，跳转到其他用户主页
      AppRouteManager.navigateToOtherUserCenter(userId);
    }
  }

  /// 发送弹幕
  void _sendBulletChat(String content) {
    // 添加弹幕到状态管理
    ActivityState.sendBullet(
      activityId: widget.activityId,
      userId: UserState.getCurrentUserInfo()?.userId ?? 'unknown',
      content: content,
    );

    // 显示成功提示
    ToastWidget.showSuccess('Bullet chat sent successfully!');
  }

  /// 处理举报分享图片
  void _handleReportShare(String shareId) {
    ReportDialog.show(
      context,
      onReportSuccess: () {
        // 举报成功后删除分享图片
        ActivityState.removeActivityShare(widget.activityId, shareId);
        ToastWidget.showSuccess('You won\'t see this again.');
      },
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        width: double.infinity,
        height: double.infinity,
        decoration: const BoxDecoration(
          image: DecorationImage(
            image: AssetImage('assets/images/common_bg.png'),
            fit: BoxFit.cover,
          ),
        ),
        child: SafeArea(
          bottom: false,
          child: Column(
            children: [
              // 顶部导航栏
              _buildTopNavigationBar(),
              // 可滑动的内容区域
              Expanded(
                child: SingleChildScrollView(
                  child: Column(
                    children: [
                      // 弹幕区域
                      _buildBulletChatSection(),
                      // 活动详情和分享图片区域
                      _buildActivityContentSection(),
                    ],
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  /// 构建顶部导航栏
  Widget _buildTopNavigationBar() {
    return Container(
      padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 12.h),
      child: Row(
        children: [
          // 返回按钮
          GestureDetector(
            onTap: () => AppRouteManager.goBack(),
            child: Row(
              children: [
                Icon(Icons.chevron_left, color: Colors.white, size: 22.w),
                SizedBox(width: 8.w),

                // 标题
                Container(
                  constraints: BoxConstraints(maxWidth: 200.w),
                  child: Text(
                        _currentActivity.title,
                        maxLines: 1,
                        overflow: TextOverflow.ellipsis,
                      )
                      .fontSize(18.sp)
                      .textColor(Colors.white)
                      .fontWeight(FontWeight.w700)
                      .fontFamily(
                        GoogleFonts.quicksand(
                          fontWeight: FontWeight.w700,
                        ).fontFamily,
                      )
                      .textAlignment(TextAlign.center),
                ),
              ],
            ),
          ),

          Spacer(),

          // 发送弹幕按钮
          AnimatedTapWidget(
            onTap: _handleSendBullet,
            child: Container(
              padding: EdgeInsets.symmetric(horizontal: 8.w, vertical: 6.h),
              decoration: BoxDecoration(
                color: Colors.white,
                borderRadius: BorderRadius.circular(36.r),
              ),
              child: Text('Bullet Chat')
                  .fontSize(13.sp)
                  .textColor(const Color(0xFFFF8A3C))
                  .fontWeight(FontWeight.w600)
                  .fontFamily(
                    GoogleFonts.quicksand(
                      fontWeight: FontWeight.w600,
                    ).fontFamily,
                  ),
            ),
          ),
        ],
      ),
    );
  }

  /// 构建弹幕区域
  Widget _buildBulletChatSection() {
    return Container(
      height: 210.h,
      margin: EdgeInsets.symmetric(horizontal: 16.w),
      child: Stack(
        clipBehavior: Clip.none,
        children: [
          // 背景图片（在z轴下方）
          Positioned.fill(
            child: Image.asset(_currentActivity.imageUrl, fit: BoxFit.contain),
          ),
          // 弹幕（在z轴上方）
          ..._activeBullets.map((bullet) => _buildBulletItem(bullet)),
        ],
      ),
    );
  }

  /// 构建单个弹幕项
  Widget _buildBulletItem(BulletItem bullet) {
    return AnimatedBuilder(
      animation: bullet.animationController,
      builder: (context, child) {
        final screenWidth = MediaQuery.of(context).size.width;
        final bulletWidth = bullet.content.length * 8.w + 24.w; // 估算弹幕宽度
        final startX = screenWidth + bulletWidth;
        final endX = -bulletWidth;
        final currentX =
            startX + (endX - startX) * bullet.animationController.value;

        return Positioned(
          top: bullet.top,
          left: currentX,
          child: ClipRRect(
            borderRadius: BorderRadius.circular(16.r),
            child: BackdropFilter(
              filter: ImageFilter.blur(sigmaX: 10.0, sigmaY: 10.0),
              child: Container(
                height: 25.h,
                padding: EdgeInsets.symmetric(horizontal: 12.w),
                decoration: BoxDecoration(
                  color: const Color(0x33FF8A3C),
                  borderRadius: BorderRadius.circular(16.r),
                  border: Border.all(
                    color: Colors.white.withOpacity(0.3),
                    width: 1.w,
                  ),
                ),
                child:
                    Text(bullet.content)
                        .fontSize(12.sp)
                        .textColor(Colors.white)
                        .fontWeight(FontWeight.w500)
                        .fontFamily(
                          GoogleFonts.quicksand(
                            fontWeight: FontWeight.w500,
                          ).fontFamily,
                        )
                        .center(),
              ),
            ),
          ),
        );
      },
    );
  }

  /// 构建活动内容区域
  Widget _buildActivityContentSection() {
    return Container(
      decoration: BoxDecoration(
        color: const Color(0xFF663507),
        borderRadius: BorderRadius.only(
          topLeft: Radius.circular(24.r),
          topRight: Radius.circular(24.r),
        ),
      ),
      child: Column(
        children: [
          // 活动详情盒子
          _buildActivityDetailBox(),

          SizedBox(height: 20.h),

          // 用户分享图片列表
          _buildShareImagesList().paddingHorizontal(16.w),
        ],
      ),
    );
  }

  /// 构建活动详情盒子
  Widget _buildActivityDetailBox() {
    return Container(
      width: double.infinity,
      padding: EdgeInsets.all(20.w),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(_currentActivity.description, style: TextStyle(height: 1.55))
              .fontSize(13.sp)
              .textColor(Colors.white)
              .fontWeight(FontWeight.w500)
              .fontFamily(
                GoogleFonts.quicksand(fontWeight: FontWeight.w500).fontFamily,
              ),

          SizedBox(height: 10.h),

          // 提示文字和勋章图片
          RichText(
            text: TextSpan(
              children: [
                TextSpan(
                  text: 'Find The Lemur And Take A Photo To Light Up The Sign',
                  style: TextStyle(
                    fontSize: 18.sp,
                    color: const Color(0xFFFF8A3C),
                    fontWeight: FontWeight.w400,
                    fontFamily:
                        GoogleFonts.rokkitt(
                          fontWeight: FontWeight.w400,
                        ).fontFamily,
                  ),
                ),
                WidgetSpan(
                  child: Padding(
                    padding: EdgeInsets.only(left: 6.w),
                    child: Image.asset(
                      _currentActivity.badgeImageUrl,
                      width: 18.w,
                      height: 18.w,
                      fit: BoxFit.cover,
                    ),
                  ),
                ),
              ],
            ),
          ),

          SizedBox(height: 20.h),

          // 上传按钮
          Center(
            child: AnimatedTapWidget(
              onTap: () {
                // 跳转到上传分享图片页面，默认选中当前活动
                AppRouteManager.navigateToUploadShare(
                  defaultActivityId: widget.activityId,
                );
              },
              child: Container(
                padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 6.h),
                decoration: BoxDecoration(
                  color: Color(0xFF842C14),
                  borderRadius: BorderRadius.circular(15.r),
                ),
                child: Text('Upload Immediately')
                    .fontSize(16.sp)
                    .textColor(Colors.white)
                    .fontWeight(FontWeight.w600)
                    .fontFamily(
                      GoogleFonts.quicksand(
                        fontWeight: FontWeight.w600,
                      ).fontFamily,
                    ),
              ).configBorderWidget(
                borderRadius: 15.r,
                borderColor: Colors.white.withOpacity(0.7),
                borderWidth: 1.w,
              ),
            ),
          ),
        ],
      ),
    );
  }

  /// 构建分享图片列表
  Widget _buildShareImagesList() {
    final shares = ActivityState.getActivityShares(widget.activityId);

    if (shares.isEmpty) {
      return Center(
        child: Text('No shared images yet')
            .fontSize(14.sp)
            .textColor(Colors.white.withOpacity(0.6))
            .fontWeight(FontWeight.w400)
            .fontFamily(
              GoogleFonts.quicksand(fontWeight: FontWeight.w400).fontFamily,
            ),
      );
    }

    // 按分享时间降序排序，最新的在最上面
    final sortedShares = List.from(shares);
    sortedShares.sort((a, b) => b.shareTime.compareTo(a.shareTime));

    return Column(
      children:
          sortedShares.map((share) => _buildShareImageCard(share)).toList(),
    );
  }

  /// 构建分享图片卡片
  Widget _buildShareImageCard(ActivityShareModel share) {
    final user = UserState.queryUserById(share.userId);
    final userName = user?.userName ?? 'Unknown User';
    final userAvatar = user?.avatar ?? 'assets/images/avatar1.png';

    return Container(
          child: Stack(
            children: [
              // 分享图片
              Container(
                width: double.infinity,
                height: 200.h,
                decoration: BoxDecoration(
                  borderRadius: BorderRadius.circular(12.r),
                  image: DecorationImage(
                    image: AssetImage(share.imageUrl),
                    fit: BoxFit.cover,
                  ),
                ),
                child: Stack(
                  children: [
                    // 上方渐变蒙层
                    Positioned(
                      top: 0,
                      left: 0,
                      right: 0,
                      height: 60.h,
                      child: Container(
                        decoration: BoxDecoration(
                          borderRadius: BorderRadius.only(
                            topLeft: Radius.circular(12.r),
                            topRight: Radius.circular(12.r),
                          ),
                          gradient: LinearGradient(
                            begin: Alignment.topCenter,
                            end: Alignment.bottomCenter,
                            colors: [
                              Colors.black.withOpacity(0.6),
                              Colors.transparent,
                            ],
                          ),
                        ),
                      ),
                    ),
                    // 下方渐变蒙层
                    Positioned(
                      bottom: 0,
                      left: 0,
                      right: 0,
                      height: 60.h,
                      child: Container(
                        decoration: BoxDecoration(
                          borderRadius: BorderRadius.only(
                            bottomLeft: Radius.circular(12.r),
                            bottomRight: Radius.circular(12.r),
                          ),
                          gradient: LinearGradient(
                            begin: Alignment.bottomCenter,
                            end: Alignment.topCenter,
                            colors: [
                              Colors.black.withOpacity(0.6),
                              Colors.transparent,
                            ],
                          ),
                        ),
                      ),
                    ),
                  ],
                ),
              ),

              // 用户头像和用户名
              Positioned(
                top: 12.h,
                left: 12.w,
                child: Row(
                  children: [
                    GestureDetector(
                      onTap: () => _handleUserAvatarTap(user?.userId ?? ''),
                      child: Container(
                        width: 44.w,
                        height: 44.w,
                        decoration: BoxDecoration(shape: BoxShape.circle),
                        child: ClipOval(
                          child: Image.asset(userAvatar, fit: BoxFit.cover),
                        ),
                      ),
                    ),
                    SizedBox(width: 8.w),
                    Text(userName)
                        .fontSize(18.sp)
                        .textColor(Colors.white)
                        .fontWeight(FontWeight.w600)
                        .fontFamily(
                          GoogleFonts.quicksand(
                            fontWeight: FontWeight.w600,
                          ).fontFamily,
                        ),
                  ],
                ),
              ),

              // 举报按钮
              Positioned(
                top: 12.h,
                right: 12.w,
                child: AnimatedTapWidget(
                  onTap: () => _handleReportShare(share.shareId),
                  child: Image.asset(
                    'assets/images/report.png',
                    width: 22.w,
                    height: 28.w,
                  ),
                ),
              ),
            ],
          ),
        )
        .configBorderWidget(
          borderRadius: 12.r,
          borderColor: Colors.white.withOpacity(0.7),
          borderWidth: 1.w,
        )
        .paddingBottom(12.w);
  }
}
